package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.response.OrderDetailRs;
import com.xmy.cultivate.service.ILklOrderService;
import com.xmy.cultivate.service.IOrderApplyService;
import com.xmy.cultivate.service.IOrderDetailService;
import com.xmy.cultivate.service.IOrganizationService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.List;

/**
 * <p>
 * 订单报名信息 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2025-05-25
 */
@RestController
@RequestMapping("/api/orderDetail")
public class OrderDetailController extends BaseController{
    @Autowired
    IOrderDetailService iOrderDetailService;
    @Autowired
    IOrderApplyService iOrderApplyService;
    @Autowired
    ILklOrderService iLklOrderService;
    @Autowired
    IOrganizationService iOrganizationService;

    @GetMapping("/getOrderList")
    public Result getOrderList(@RequestParam(value = "pageNum", defaultValue = "-1") Integer pageNum,
                          @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                          @RequestParam(value = "payType") String payType,   //0:待支付 1:已支付 2交易关闭（2：已失效 3：取消订单）
                          @RequestParam(value = "yearPart", required = false) String yearPart,
                          @RequestParam(value = "quarterNum", required = false) String quarterNum,
                          @RequestParam(value = "startDate", required = false) String startDate,
                          @RequestParam(value = "endDate", required = false) String endDate,
                          @RequestParam(value = "schoolId", required = false) String schoolId,
                          @RequestParam(value = "subjectsId", required = false) String subjectsId,
                          @RequestParam(value = "studentName", required = false) String studentName
    ) {

        if (StringUtils.isBlank(schoolId)) {
            schoolId =this.baseSchoolIdStr;
        }
        Long createdId = this.adminId;
        if (this.adminId.equals(1568138350324350975L)){
            createdId = null;//管理员查看所有的，这里设置为空
        }else {
            QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("schoolmaster_id",this.adminId);
            long count = iOrganizationService.count(queryWrapper);
            if (count > 0){
                createdId = null;//校长查看权限校区，这里设置为空
            }
        }


        Page<OrderDetailRs> iPage = new Page<>(pageNum, pageSize);
        //交易关闭包括（2：已失效 3：取消订单）
        if (payType.equals("2")){
            payType = "2,3";
        }
        if (!StringUtils.isBlank(startDate)){
            startDate = startDate + " 00:00:00";
        }
        if (!StringUtils.isBlank(endDate)){
            endDate = endDate + " 23:59:59";
        }
        iOrderDetailService.getOrderDetailList(iPage,createdId, payType,yearPart,  quarterNum, startDate, endDate, schoolId,subjectsId, studentName);
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    @GetMapping("/orderDetail")
    public Result orderDetail(@RequestParam(value = "id" ) Long id) {
//        if (StringUtils.isBlank(id)){
//            return new Result(Code.ERROR, "", "id不能为空");
//        }
        OrderDetail orderDetail = iOrderDetailService.getById(id);

        if (orderDetail == null){
            return new Result(Code.ERROR, "", "该订单不存在");
        }
        OrderDetailRs orderDetailRs =iOrderDetailService.orderDetailForId(id);

        return new Result(Code.OK, orderDetailRs,  Code.GET_OK_MSG);

    }
    /**
     * 取消订单
     * @param orderDetail
     * @return
     */
    @PutMapping("/cancelOrder")
    @Transactional(rollbackFor = Exception.class)
    public Result cancelOrder(@RequestBody OrderDetail orderDetail) {
        OrderDetail orderDetail1 = iOrderDetailService.getById(orderDetail.getId());
        if (orderDetail1 == null){
            return new Result(Code.ERROR, "", "该订单不存在");
        }
        if (!orderDetail1.getPayType().equals(0)){
            return new Result(Code.ERROR, "", "该订单状态不能取消，取消失败");
        }


        Long orderId = orderDetail1.getOrderId();
        String lklOrderNo = orderDetail1.getLklOrderNo();
//        if (orderId == null){
//            return new Result(Code.ERROR, "", "orderId为空，无法取消");
//        }
//        if (StringUtils.isBlank(lklOrderNo)){
//            return new Result(Code.ERROR, "", "lklOrderNo为空，无法取消");
//        }
        boolean update = iOrderDetailService.updateById(orderDetail);
        if (update) {


            //订单表
            UpdateWrapper<OrderApply> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id",orderId);
            updateWrapper.set("pay_type",orderDetail.getPayType());
            iOrderApplyService.update(updateWrapper);

            UpdateWrapper<LklOrder> lklOrderUpdateWrapper = new UpdateWrapper<>();
            lklOrderUpdateWrapper.eq("out_order_no",lklOrderNo);
            lklOrderUpdateWrapper.set("pay_type",orderDetail.getPayType());
            iLklOrderService.update(lklOrderUpdateWrapper);

            return new Result(Code.UPDATE_OK, "", "订单取消成功");
        }
        return new Result(Code.UPDATE_ERROR, "", "订单取消失败");

    }

}
